package com.test.reggieadmin.model.fragment.cpgl;

import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;

import com.bumptech.glide.Glide;
import com.lxj.xpopup.XPopup;
import com.test.reggieadmin.R;
import com.test.reggieadmin.base.BaseFragment;
import com.test.reggieadmin.base.BaseRVAdapter;
import com.test.reggieadmin.base.BaseRVHolder;
import com.test.reggieadmin.bean.BaseBean;
import com.test.reggieadmin.bean.DishPageBean;
import com.test.reggieadmin.bean.EmployeeBean;
import com.test.reggieadmin.bean.GetDataType;
import com.test.reggieadmin.bean.State;
import com.test.reggieadmin.databinding.FragmentCpglBinding;
import com.test.reggieadmin.http.API;
import com.test.reggieadmin.model.dish.AddDishActivity;
import com.yechaoa.yutils.GsonUtil;
import com.yechaoa.yutils.ToastUtil;
import com.yechaoa.yutils.YUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 菜品管理
 */
public class CpglFragment extends BaseFragment<FragmentCpglBinding, CpglPrensenter> implements
        CpglView, View.OnClickListener {

    private BaseRVAdapter<DishPageBean.DataBean.RecordsBean> adapter;
    private int page = 1;
    private int pageSize = 10;
    private int ADD = 201;
    private int UPDATE = 202;
    private int pos;
    private int status;
    private EmployeeBean employeeBean;

    @Override
    protected CpglPrensenter createPresenter() {
        return new CpglPrensenter(this);
    }

    @Override
    protected void initView() {
        viewBinding.btnSearch.setOnClickListener(this);
        viewBinding.fabAdd.setOnClickListener(this);

        employeeBean = GsonUtil.GsonToBean(String.valueOf(API.kv.decodeString(State.employee)), EmployeeBean.class);
    }

    @Override
    protected void initData() {
        YUtils.showLoading("加载中...");
        presenter.dishPage(page, pageSize, viewBinding.etName.getText().toString().trim(),
                GetDataType.GETDATA);//查询

        adapter = new BaseRVAdapter<DishPageBean.DataBean.RecordsBean>(R.layout.item_dish) {
            @Override
            public void onBindVH(BaseRVHolder holder, DishPageBean.DataBean.RecordsBean data, int position) {
                TextView tv_status = holder.getView(R.id.tv_status);
                CircleImageView iv = holder.getView(R.id.iv);
                LinearLayout ll_cotent = holder.getView(R.id.ll_cotent);
                TextView tv_status_on = holder.getView(R.id.tv_status_on);
                TextView tv_delete = holder.getView(R.id.tv_delete);

                Glide.with(getActivity()).load(API.kv.decodeString(State.ip) + "/common/download?name=" +
                        data.getImage())/*.diskCacheStrategy(DiskCacheStrategy.NONE)*/
                        .placeholder(R.drawable.icon_no_data).into(iv);
                holder.setText(R.id.tv_name, data.getName());
                holder.setText(R.id.tv_type, data.getCategoryName());
                holder.setText(R.id.tv_peice, "￥" + data.getPrice());
                if (data.getStatus() == 1) {
                    tv_status.setText("起售");
                    tv_status_on.setText("停售");
                } else {
                    tv_status.setText("停售");
                    tv_status_on.setText("起售");
                }
                holder.setText(R.id.tv_updateTime, data.getUpdateTime());

                tv_status_on.setOnClickListener(v -> {//起售、停售
                    new XPopup.Builder(getActivity()).asConfirm("提示",
                            "确定" + (data.getStatus() == 1 ? "停售" : "起售") + "该套餐吗？",
                            () -> {
                                pos = position;
                                status = data.getStatus();

                                YUtils.showLoading("提交中...");
                                Map<String, Object> mapUpdate = new HashMap<>();
                                mapUpdate.put("updateUser", employeeBean.getData().getUsername());
                                mapUpdate.put("id", data.getId());
                                mapUpdate.put("status", (status == 1 ? 0 : 1));
                                presenter.updateDish(mapUpdate);//修改菜品
                            })
                            .show();
                });

                ll_cotent.setOnClickListener(v -> {//编辑
                    Intent intent = new Intent(getActivity(), AddDishActivity.class);
                    intent.putExtra("id", data.getId());
                    intent.putExtra("categoryId", data.getCategoryId());
                    startActivityForResult(intent, UPDATE);
                });

                tv_delete.setOnClickListener(v -> {//删除菜品
                    new XPopup.Builder(getActivity()).asConfirm("提示", "确定删除该菜品吗",
                            () -> {
                                pos = position;
                                YUtils.showLoading("删除中...");
                                presenter.deleteDish(data.getId());//删除菜品
                            }).show();
                });
            }
        };

        empty("暂无数据");

        viewBinding.mRefreshLayout.setOnRefreshListener(refreshLayout -> {//下拉刷新
            page = 1;
            presenter.dishPage(page, pageSize, viewBinding.etName.getText().toString().trim(),
                    GetDataType.REFRESH);
        });

        viewBinding.mRefreshLayout.setOnLoadMoreListener(refreshLayout -> {//上拉加载更多
            page++;
            presenter.dishPage(page, pageSize, viewBinding.etName.getText().toString().trim(),
                    GetDataType.LOADMORE);
        });

        viewBinding.mRecyclerView.setAdapter(adapter);
        viewBinding.mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 1));//列数设置
    }

    @Override
    public void dishPageError(String msg) {
        YUtils.hideLoading();
        viewBinding.mRefreshLayout.finishRefresh();
        viewBinding.mRefreshLayout.finishLoadMore();

        empty(msg);
    }

    @Override
    public void dishPageSuccess(DishPageBean bean, int type) {
        YUtils.hideLoading();

        if (bean.getCode() == 200) {
            List<DishPageBean.DataBean.RecordsBean> pageList = bean.getData().getRecords();
            switch (type) {
                case GetDataType.GETDATA://获取数据成功
                    adapter.setNewData(pageList);
                    viewBinding.mRefreshLayout.setNoMoreData(false);
                    break;
                case GetDataType.REFRESH://刷新成功
                    adapter.setNewData(pageList);
                    viewBinding.mRefreshLayout.finishRefresh();
                    viewBinding.mRefreshLayout.setNoMoreData(false);
                    break;
                case GetDataType.LOADMORE://加载成功
                    if (pageList != null && !pageList.isEmpty()) {
                        adapter.addData(pageList);
                        if (pageList.size() < pageSize) {
                            viewBinding.mRefreshLayout.finishLoadMoreWithNoMoreData();
                        } else {
                            viewBinding.mRefreshLayout.finishLoadMore();
                        }
                    } else {
                        viewBinding.mRefreshLayout.finishLoadMoreWithNoMoreData();
                    }
                    break;
            }
        } else {
            ToastUtil.showCenter(bean.getMsg());
            viewBinding.mRefreshLayout.finishRefresh();
            viewBinding.mRefreshLayout.finishLoadMore();
        }
    }

    @Override
    public void updateDishSuccess(BaseBean bean) {
        YUtils.hideLoading();
        ToastUtil.showCenter(bean.getMsg());
        if (bean.getCode() == 200) {
            adapter.getData().get(pos).setStatus((status == 1 ? 0 : 1));
            adapter.notifyItemChanged(pos);
        }
    }

    @Override
    public void onError(String msg) {
        YUtils.hideLoading();
        ToastUtil.showCenter(msg);
    }

    @Override
    public void deleteDishSuccess(BaseBean bean) {
        YUtils.hideLoading();
        ToastUtil.showCenter(bean.getMsg());
        if (bean.getCode() == 200) {
            adapter.remove(pos);
        }
    }

    private void empty(String msg) {
        View empty = LayoutInflater.from(getActivity()).inflate(R.layout.layout_no_data, null, false);
        TextView tv_tip = empty.findViewById(R.id.tv_tip);
        tv_tip.setText(msg);
        adapter.setEmptyView(empty);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ADD && resultCode == Activity.RESULT_OK) {
            page = 1;
            presenter.dishPage(page, pageSize, viewBinding.etName.getText().toString().trim(),
                    GetDataType.REFRESH);
        } else if (requestCode == UPDATE && resultCode == Activity.RESULT_OK) {
            page = 1;
            presenter.dishPage(page, pageSize, viewBinding.etName.getText().toString().trim(),
                    GetDataType.REFRESH);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_search://搜索
                YUtils.showLoading("加载中...");
                page = 1;
                presenter.dishPage(page, pageSize, viewBinding.etName.getText().toString().trim(),
                        GetDataType.REFRESH);
                break;
            case R.id.fab_add://添加菜品
                Intent intent = new Intent(getActivity(), AddDishActivity.class);
                startActivityForResult(intent, ADD);
                break;
            default:
                break;
        }
    }
}